// This file is a part of ChaosDB.
// Copyright (C) 2012 ChaoJianPeng
// email:chaojianpeng@gmail.com
//
// ChaosDB is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ChaosDB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

/*
 * cmalloc.cpp
 *
 *  Created on: 2012-3-4
 *      Author: chao
 */



#include "cmalloc.h"
#include "stdio.h"
#include "string.h"

size_t used_memory = 0;


void* cmalloc(int size) {
	void *ptr = malloc(size + PREFIX_SIZE);
	memcpy(ptr, &size, PREFIX_SIZE);
	used_memory += size + PREFIX_SIZE;
	return (void*) ptr + PREFIX_SIZE;
}

void cfree(void* ptr) {
	void* p = ptr - PREFIX_SIZE;
	size_t realsize = cmalloc_size(ptr);
	used_memory -= realsize;
	free(p);
}

/**
 * 不需要实际pointer
 * 获取整个数据块的大小
 */
int cmalloc_size(void* ptr) {
	void *realptr = ptr - PREFIX_SIZE;
	int size = *((int*)realptr);
	return size + PREFIX_SIZE;
}

/**
 * 不需要实际pointer
 * 获取数据的大小
 */
int getSize(void* ptr){
	void *realptr = ptr - PREFIX_SIZE;
	int size = *((int*)realptr);
	return size;
}

size_t getUsed() {
	return used_memory;
}
